import { ListRawState } from '../../views/home'
interface CarState {
	car: CarRawState[]
}

interface CarRawState extends ListRawState {
	// 数量
	count: number
	// 状态
	state: boolean
}

const initState: CarState = {
	car: JSON.parse(localStorage.getItem('carList') || '[]')
}
// 常量
// 购物车添加
const ADDTOCAR = 'ADDTOCAR'
// 购物租车数量+
const ADDCARCOUNT = 'ADDCARCOUNT'
// 购物租车数量-
const SUBCARCOUNT = 'SUBCARCOUNT'
// 单选修改
const SWITCHCARSTATE = 'SWITCHCARSTATE'
// 全选修改
const SWITCHCARSTATEALL = 'SWITCHCARSTATEALL'


interface SwitchCarStateAll {
	type: typeof SWITCHCARSTATEALL
	payload: boolean
}

export function switchCarStateAllActionCreator(payload: boolean): SwitchCarStateAll {
	return { type: SWITCHCARSTATEALL, payload }
}


interface SwitchCarState {
	type: typeof SWITCHCARSTATE
	payload: CarRawState
}

export function switchCarStateActionCreator(payload: CarRawState): SwitchCarState {
	return { type: SWITCHCARSTATE, payload }
}


interface SubCarCount {
	type: typeof SUBCARCOUNT
	payload: CarRawState
}

export function subCarCountActionCreator(payload: CarRawState): SubCarCount {
	return { type: SUBCARCOUNT, payload }
}


interface AddCarCount {
	type: typeof ADDCARCOUNT
	payload: CarRawState
}

export function addCarCountActionCreator(payload: CarRawState): AddCarCount {
	return { type: ADDCARCOUNT, payload }
}


interface AddToCar {
	type: typeof ADDTOCAR
	payload: CarRawState
}

export function addToCarActionCreator(payload: CarRawState): AddToCar {
	return { type: ADDTOCAR, payload }
}

type CarAction = AddToCar | AddCarCount | SubCarCount | SwitchCarState | SwitchCarStateAll

const reducer = (state = initState, action: CarAction): CarState => {
	switch (action.type) {
		case ADDTOCAR: {
			// 加入购物车
			//  1. 加入的数据是否存在购物车
			const item = state.car.find(v => v.id === action.payload.id)
			// 2. 存在 数量递增
			if (item) { item.count++ }
			// 3. 不存在 添加新数据
			else {
				state.car.push(action.payload)
			}
			return {
				...state,
				car: [...state.car]
			}
		}
		case ADDCARCOUNT: {
			//  1. 加入的数据是否存在购物车
			const item = state.car.find(v => v.id === action.payload.id)
			// 2. 存在 数量递增
			if (item) { item.count++ }
			return {
				...state,
				car: [...state.car]
			}
		}

		case SUBCARCOUNT: {
			//  1. 加入的数据是否存在购物车
			const item = state.car.find(v => v.id === action.payload.id)
			// 2. 存在 数量递增
			if (item) { item.count-- }
			return {
				...state,
				car: [...state.car]
			}
		}

		case SWITCHCARSTATE: {
			//  1. 加入的数据是否存在购物车
			const item = state.car.find(v => v.id === action.payload.id)
			// 2. 存在 数量递增
			if (item) { item.state = !item.state }
			return {
				...state,
				car: [...state.car]
			}

		}
		case SWITCHCARSTATEALL: {
			state.car.forEach(v => {
				v.state = action.payload
			})

			return {
				...state,
				car: [...state.car]
			}
		}
		default: return state
	}
}

export default reducer


